;;; Guile-GCC --- Guile extension to GCC.               -*- coding: utf-8 -*-
;;; Copyright (C) 2012 Ludovic Courtès
;;;
;;; This file is part of Guile-GCC.
;;;
;;; Guile-GCC is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; Guile-GCC is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with Guile-GCC.  If not, see <http://www.gnu.org/licenses/>.

(define-module (test-cgraph)
  #:use-module (gcc)
  #:use-module (gcc cgraph)
  #:use-module (gcc gimple)
  #:use-module (srfi srfi-1))

;; Test whether a pass can be inserted at a point where the cgraph is built,
;; whether it can traverse the cgraph, and whether it can access the
;; corresponding tree or GIMPLE nodes.

(define call-graph-info-pass
  (make-pass "call-graph-info" GIMPLE_PASS
             (lambda ()
               (let ((n (cgraph-get-node (current-function-decl))))
                 (and (eq? (cgraph-node-decl n) (current-function-decl))
                      (inform (decl-source-location (cgraph-node-decl n))
                              "~a callers, ~a callees"
                              (length (cgraph-node-callers n))
                              (length (cgraph-node-callees n))))
                 (for-each (lambda (edge)
                             (let ((call (cgraph-edge-call-statement edge)))
                               (and (gimple? call)
                                    (= (gimple-code call) GIMPLE_CALL)
                                    (let* ((fn (gimple-call-fndecl call))
                                           (id (decl-name fn)))
                                     (inform (gimple-source-location call)
                                             "call to ~a"
                                             (identifier-string id))))))
                           (cgraph-node-callees n)))

               ;; Nothing left to do.
               0)))

;; Register a pass after `*build_cgraph_edges', which is the one that builds
;; the cgraph nodes.
(register-pass "guile" call-graph-info-pass "*build_cgraph_edges"
               (pass-position after))

;; Register a callback to be called after most of the optimization passes,
;; including inlining.
(register-callback "guile" PLUGIN_FINISH
                   (lambda ()
                     (or (pair? (cgraph-nodes))
                         (error-at %unknown-location "no nodes"))))
